package com.gxl.butt.interceptor;

import com.gxl.butt.zkutil.DistributedLock;
import com.gxl.butt.zkutil.ZkOperator;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.gxl.butt.zkutil.ZkOperator.secskill;

/**
 * Created by guoxiaolin on 2018/7/14.
 */

public class ZKLockInterceptor extends HandlerInterceptorAdapter {//此处一般继承HandlerInterceptorAdapter适配器即可

    /**
     * 在DispatcherServlet之前执行
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String sid =request.getParameter("topic.openid");
//		String sid  = request.getSession().getId();
        DistributedLock lock = ZkOperator.getZkLock("suo" + sid);
        lock.lock();
        secskill();
        request.setAttribute("dlock",lock);
        System.out.println(Thread.currentThread().getName() + "正在运行,userSessionId = " + sid);
        System.out.println("===========HandlerInterceptor1 preHandle");

        return true;
    }


    /**
     * 在controller执行之后的DispatcherServlet之后执行
     * */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


        System.out.println("===========HandlerInterceptor1 postHandle");
    }

    /**
     * 在页面渲染完成返回给客户端之前执行
     * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        DistributedLock lock = (DistributedLock) request.getAttribute("dlock");
        /* 释放 zookeeper 分布式锁 */
        if (lock != null) {
            lock.unlock();
        }
        System.out.println("===========HandlerInterceptor1 afterCompletion");
    }
}